<template>
  <view class="container">
    <view class="auth-header">
      <view class="auth-logo">
        <image :src="src" mode=""></image>
        <text class="auth-title">贝好拍</text>
      </view>
    </view>

    <view class="auth-box">
      <!-- 登录方式选择 -->
      <!-- <view class="mode-section">
        <u-subsection class="subsection" mode="subsection" fontSize="15" :list="loginModeList" :current="currentModeIndex" @change="handleModeChange"></u-subsection>
      </view> -->
      <u-gap height="40"></u-gap>
      <view class="contents">
        <view class="c-left">
          <view class="agreement-content" @click="toggleConsent">
            <view class="checkbox-wrapper">
              <view class="custom-checkbox" :class="{ 'checked': consent }">
                <u-icon v-if="consent" name="checkmark" color="#FFFFFF" size="12"></u-icon>
              </view>
            </view>
            <view class="agreement-text-wrapper">
              <view class="agreement-line">
                <text class="agreement-text">登录代表您已同意</text>
                <text class="color-bs f-weight" @click.stop="clickNotice(1)">《用户协议》</text>
                <text class="agreement-text">和</text>
                <text class="color-bs f-weight" @click.stop="clickNotice(2)">《隐私政策》</text>
              </view>
            </view>
          </view>
        </view>
      </view>
      <!-- 登录表单 -->
      <u--form labelPosition="left" :model="formData" :rules="rules" ref="form">
        <view class="btn-group">
          <button class="auth-btn bg" type="default" open-type="getPhoneNumber"
                  @getphonenumber="getPhoneNumber">一键登录</button>
        </view>
      </u--form>
    </view>
  </view>
</template>

<script>
import {
  log,
  getUser
} from '../../api/login.js'
import config from '@/common/config'
export default {
  data() {
    return {
      consent: false,
      currentModeIndex: 0,
      loginModeList: ['密码登录', '验证码登录'],
      inputType: 'password',
      codeDisabled: false,
      codeTips: '',
      src: config.baseImgUrl + '/minis/logo/bhp.png',
      formData: {
        mobile: '15896325478',
        password: '546648',
        code: ''
      },
      rules: {
        mobile: [{
          type: 'integer',
          required: true,
          message: '请填写手机号',
          trigger: ['blur', 'change']
        },
          {
            // 自定义验证函数，见上说明
            validator: (rule, value, callback) => {
              // 上面有说，返回true表示校验通过，返回false表示不通过
              // uni.$u.test.mobile()就是返回true或者false的
              return uni.$u.test.mobile(value)
            },
            message: '手机号码不正确',
            // 触发器可以同时用blur和change
            trigger: ['change', 'blur']
          }
        ],
        password: {
          type: 'string',
          min: 4,
          max: 16,
          required: true,
          message: '密码长度4-16位密码',
          trigger: ['blur', 'change']
        },
        code: {
          type: 'integer',
          len: 4,
          required: true,
          message: '请填写4位验证码',
          trigger: ['blur', 'change']
        }
      }
    }
  },
  onLoad() {
    this.login()
  },
  onReady() {

  },
  methods: {
    // 登录
    login() {
      uni.login({
        provider: 'weixin',
        success: (res) => {

        },
        fail: () => {
          uni.showToast({
            title: "微信登录授权失败",
            icon: "none"
          });
        }
      })
    },
    clickNotice(i) {
      if (i == 1) {
        uni.navigateTo({
          url: "/pages/agreement/user"
        })
      }
      if (i == 2) {
        uni.navigateTo({
          url: "/pages/agreement/privacy"
        })
      }
    },
    //获取手机code
    getPhoneNumber(e) {
      const c = this.consent

      if (c) {
        if (e.detail.code) {
          this.miniLogin(e.detail.code)
        }
      } else {
        uni.$u.toast("请勾选您已同意授权登录！")
      }

    },
    //登录
    miniLogin(phoneCode) {
      let that = this
      uni.showModal({
        mask: true,
        title: '授权登录',
        content: '授权微信登录，使用更多功能！',
        success(ress) {
          if (ress.confirm) {
            uni.getUserProfile({
              desc: '获取你的昵称，头像',
              success(userRes) {
                if (userRes.errMsg == 'getUserProfile:ok' && userRes.userInfo !=
                    undefined) {
                  let userinfo = userRes.userInfo
                  uni.login({
                    provider: 'weixin',
                    success(res) {
                      let parmas = {
                        encryptedData: '',
                        iv: '',
                        loginCode: res.code,
                        phoneCode: phoneCode,
                        signature: userRes.signature
                      }
                      log(parmas).then(loginRes => {
                        if (loginRes.code == 0) {
                          // that.$store.commit('setToken',loginRes.data.accessToken)
                          uni.setStorageSync('token',
                              loginRes.data.accessToken)
                        }
                      }).then(loginResT => {
                        getUser().then(infoRes => {
                          if (infoRes.code == 0) {
                            uni.$u.toast('登录成功')
                            uni.setStorageSync(
                                'userInfo',
                                infoRes.data)
                            setTimeout(() => {
                              uni.switchTab({
                                url: '/pages/index/fanyuanlist'
                              })
                            }, 1000)
                          }
                        })
                      })
                    }
                  })
                }
              },
            })
          }
        }
      })
    },
    toggleConsent() {
      this.consent = !this.consent
    },
    groupChange(n) {
      console.log(n)
    },
    radioChange(n) {
      console.log(n)
      // 根据当前值切换状态
      this.consent = !this.consent
      // 如果取消勾选，清空单选框的值
      if (!this.consent) {
        this.radiovalue1 = ''
      }
    },
    handleModeChange(index) {
      if (index !== this.currentModeIndex) {
        this.currentModeIndex = index
        this.$refs.form.clearValidate()
      }
    },
    codeChange(text) {
      this.codeTips = text
    },
    getCode() {
      const mobile = this.formData.mobile
      if (!mobile) {
        uni.$u.toast('请填写手机号')
      } else if (!uni.$u.test.mobile(mobile)) {
        uni.$u.toast('手机号格式不正确')
      } else if (this.$refs.uCode.canGetCode) {
        // 模拟向后端请求验证码
        uni.showLoading({
          title: '正在获取验证码'
        })

        //scene:1登陆获取验证码场景
        sendSmsCode({
          mobile: mobile,
          scene: 1
        }).then(res => {
          //console.log(res)
          uni.hideLoading()
          uni.$u.toast('验证码已发送')
          // 通知验证码组件内部开始倒计时
          this.$refs.uCode.start()
        })
      } else {
        uni.$u.toast('倒计时结束后再发送')
      }
    },
    handleSubmit() {
      this.$refs.form.validate().then(res => {
        uni.login({
          provider: 'weixin',
          success: res => {
            let data = this.formData
            data.socialType = null //WECHAT_MINI_APP 先指定固定值
            data.socialCode = res.code
            data.socialState = Math.random() // 该参数没有实际意义暂时传随机数
            this.mobileLogin(data)
          },
          fail: res => {
            this.mobileLogin(this.formData)
          }
        })
      })
    },
    mobileLogin(data) {
      // this.$store.dispatch('Login', { type: this.currentModeIndex, data: data }).then(res => {
      uni.$u.toast('登录成功')
      setTimeout(() => {
        uni.switchTab({
          url: '/pages/index/fanyuanlist'
        })
      }, 300)
      // })
    }
  }
}
</script>

<style lang="scss" scoped>
.auth-header {
  height: 400rpx;
  @include flex-center;

  .auth-logo {
    image {
      width: 150rpx;
      height: 150rpx;
    }
    
    .auth-title {
      display: block;
      font-size: 40rpx;
      font-weight: bold;
      color: #333;
      margin-top: 20rpx;
      text-align: center;
    }
  }
}

.contents {
  text-align: center;
  padding: 0 30rpx;
}

.c-left {
  float: left;
  text-align: left;
  font-size: 28rpx;
  color: #666;
  width: 100%;
  
  ::v-deep .u-radio {
    margin-bottom: 20rpx;
    
    .u-radio__icon {
      margin-right: 10rpx;
    }
  }
}

.agreement-content {
  display: flex;
  align-items: flex-start;
  gap: 10rpx;
  padding: 10rpx 0;
}

.checkbox-wrapper {
  padding-top: 4rpx;
}

.custom-checkbox {
  width: 36rpx;
  height: 36rpx;
  border: 2rpx solid #c8c9cc;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
  
  &.checked {
    background-color: #4e5ff9;
    border-color: #4e5ff9;
  }
}

.agreement-text-wrapper {
  flex: 1;
}

.agreement-line {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.agreement-text {
  color: #666;
  font-size: 28rpx;
  line-height: 1.5;
}

.agreement-links {
  display: flex;
  align-items: center;
  gap: 5rpx;
}

.color-bs {
  color: #4e5ff9;
}

.f-weight {
  font-weight: bold;
}

.login-text {
  float: left;
  font-size: 26rpx;
}

.auth-box {
  @include flex-center(column);

  .mode-section {
    width: 600rpx;

    .subsection {
      height: 60rpx;
    }
  }

  .btn-group {
    width: 600rpx;

    .auth-btn {
      line-height: 90rpx;
      font-size: 32rpx;
    }

    .bg {
      background-color: #4e5ff9;
      color: #fff;
      font-size: 14px;
      margin-top: 40rpx;
    }
  }
}
</style>